module.exports = app => {
    const dayjs = require('dayjs')
    const express = require('express')
    const router = express.Router({
        mergeParams: true
    })
    let jwt = require('jsonwebtoken')
    const AdminUser = require('../../models/user')
    const assert = require('http-assert')
    // 创建
    router.post('/', async (req, res) => {
        console.log(req.body)
        const model = await req.Model.create(req.body)
        res.send({
            code: 200,
            msg: '新增成功',
            data: model
        })
    })
    // 查询
    router.get('/', async (req, res) => {
        console.log(req.query, req.query.query)
        let items = []
        // 获取当日数据
        if (req.query.time == 'today') {
            const today = dayjs(new Date()).format('YYYY-MM-DD')
            const data  = await req.Model.find()
            data.map(item => {
                if (dayjs(today).isSame(dayjs(item.addTime))) {
                    items.push(item)
                }
            })
        } else if (req.query.query) {
            console.log(req.query.query)
            items = await req.Model.find({name: {$regex: req.query.query} })
        } else {
            items = await req.Model.find()
        }
        res.send({
            code: 200,
            msg: '查询成功',
            items
        })
    })
    // 根据id查询
    router.get('/:id', async (req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send({
            code: 200,
            msg: '查询成功',
            data: model
        })
    })
    // 修改
    router.put('/:id', async(req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send({
            code: 200,
            msg: '查询成功',
            data: model
        })
    })
    // 删除
    router.delete('/:id', async(req, res) => {
        await req.Model.findByIdAndDelete(req.params.id)
        res.send({
            code: 200,
            msg: '删除成功'
        })
    })
    //   // 权限校验中间件
    //   const authMiddleWare = async(req, res, next) => {
    //     // console.log(req.query.platform)
    //     if (!req.query.platform) {
    //         const token = String(req.headers.authorization || '').split(' ').pop()
    //         // console.log(req.headers, token)
    //         assert(token, 401, '没有token')
    //         const { id } = jwt.verify(token, app.get('key'))
    //         assert(id, 401, 'token有误')
    //         req.user = await AdminUser.findById(id)
    //         assert(req.user, 401, '暂无用户名')
    //         // console.log(req.user)
    //         await next()
    //     } else {
    //         await next()
    //     }
    // }
    // 资源中间件
    const resourceMiddleMare = async(req, res, next) => {
        const modelName = require('inflection').classify(req.params.resource)
        req.Model = require(`../../models/${modelName}`)
        next()
    }
    app.use('/shopping/api/reset/:resource', resourceMiddleMare,  router)

    const multer = require('multer')
    let storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, __dirname + '/../../uploads')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
    })
    const upload = multer({
        storage: storage
    })
    // 上传
    app.post('/shopping/api/uploads', upload.single('file'), async(req, res) => {
        console.log(req)
        res.send({
            code: 200,
            msg: '上传成功',
            data: {
                url: `http://localhost:3001/uploads/${req.file.filename}`,
                name: req.file.filename
            }
        })
    })
    
    //  登录接口
    app.post('/shopping/api/login', async(req, res) => {
        // 获取用户名
        const { userName, password} = req.body
        const user = await AdminUser.findOne({userName: userName}).select('+password')
        assert(user, 403, '用户不存在')
        // 校验密码
        assert(password === user.password, 403, '用户密码不正确')
        // 生成token
        const token = jwt.sign({id: user._id}, app.get('key'))
        res.send({
            code: 200,
            msg: '登录成功',
            token
        })
    })

       //  创建用户
       app.post('/shopping/api/loginCreat', async(req, res) => {
        // 获取用户名
        // const { userName, password} = req.body
        await AdminUser.create(req.body)
        // const user = await AdminUser.findOne({userName: userName}).select('+password')
        res.send({
            code: 200,
            msg: '创建成功'
        })
    })
    
    // 错误处理函数
    app.use(async( err, req, res, next) => {
        res.status(err.statusCode).send({
            code: err.statusCode,
            msg: err.message
        })
    })
}

